import re
from typing import List, Dict


def parse_fixed_files_from_llm(answer: str) -> List[Dict[str, str]]:
    """Parse LLM answer and return a list of fixed files.

    The parser looks for fenced code blocks and common markers. It returns
    items like {"name": ..., "path": ..., "content": ...}.
    """
    fixed_files = []

    # 1) Fenced code blocks with an optional language that may include a filename
    fence = re.compile(r"```(?P<lang>[A-Za-z0-9_\-\.]+)?\n(?P<code>[\s\S]*?)\n```", re.MULTILINE)
    for m in fence.finditer(answer):
        code = m.group("code")
        lang = (m.group("lang") or "").strip()
        name = None
        if lang and "." in lang:
            # sometimes models put filename as the 'language' portion
            name = lang
        if not name:
            # fallback: look for explicit BEGIN markers near the block
            m2 = re.search(r"====\s*BEGIN\s*([^=\n]+)\s*====", answer)
            if m2:
                name = m2.group(1).strip()
        if name and code:
            fixed_files.append({"name": name, "path": name, "content": code})

    # 2) If nothing parsed, try to heuristically extract a single code area
    if not fixed_files:
        # try to find the largest fenced block
        blocks = [b.group("code") for b in fence.finditer(answer)]
        if blocks:
            content = max(blocks, key=len)
            fixed_files.append({"name": "fixed_code.txt", "path": "fixed_code.txt", "content": content})

    return fixed_files
